import React, { useEffect, useState, useRef } from "react";
import { Card, Col, Row, Avatar, Drawer } from "antd";
import {
  // EditOutlined,
  // EllipsisOutlined,
  PieChartOutlined
} from "@ant-design/icons";
import axios from "axios";
import CardList from "../../../components/home/CardList";
import * as echarts from "echarts";
import _ from "lodash";

const { Meta } = Card;

export default function Home() {
  const [viewList, setViewList] = useState([]);
  const [starList, setStarList] = useState([]);
  const [visible, setVisible] = useState(false);
  const [pieChart, setPieChart] = useState(false);
  const [pieList, setPieList] = useState(false);
  const barRef = useRef();
  const pieRef = useRef();
  const {
    username,
    region,
    role: { roleName }
  } = JSON.parse(localStorage.getItem("token"));
  useEffect(() => {
    axios
      .get(`/news?_expand=category&_sort=view&_limit=6&_order=desc`)
      .then(({ data }) => {
        setViewList(data);
      });
    axios
      .get(`/news?_expand=category&_sort=star&_limit=6&_order=desc`)
      .then(({ data }) => {
        setStarList(data);
      });
    axios.get(`/news?_expand=category`).then(({ data }) => {
      let barList = _.groupBy(data, v => v.category.title);
      renderBarChart(barList);
    });
    return () => {
      window.onresize = null;
    };
  }, []);
  useEffect(() => {
    axios.get(`/news?_expand=category&author=${username}`).then(({ data }) => {
      let obj = _.groupBy(data, v => v.category.title);
      let list = Object.entries(obj).map(v => ({
        name: v[0],
        value: v[1].length
      }));
      setPieList(list);
    });
  }, [username]);
  const renderBarChart = barList => {
    // 基于准备好的dom，初始化echarts实例
    var myChart = echarts.init(barRef.current);
    // 绘制图表
    myChart.setOption({
      title: {
        text: "新闻分类图示"
      },
      tooltip: {},
      xAxis: {
        data: Object.keys(barList),
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        minInterval: 1
      },
      series: [
        {
          name: "数量",
          type: "bar",
          data: Object.values(barList).map(v => v.length)
        }
      ]
    });
    window.onresize = () => {
      myChart.resize();
    };
  };
  const renderPieChart = () => {
    if (pieChart) return;
    let myChart = echarts.init(pieRef.current);
    setPieChart(myChart);
    var option;
    option = {
      title: {
        text: "个人新闻数据分析",
        left: "center"
      },
      tooltip: {
        trigger: "item"
      },
      legend: {
        orient: "vertical",
        left: "left"
      },
      series: [
        {
          name: "数据分析",
          type: "pie",
          radius: "50%",
          data: pieList,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)"
            }
          }
        }
      ]
    };
    option && myChart.setOption(option);
  };
  return (
    <div>
      <Row gutter={16}>
        <CardList title="用户最常浏览" dataSource={viewList} />
        <CardList title="用户点赞最多" dataSource={starList} />
        <Col span={8}>
          <Card
            cover={
              <img
                alt="example"
                src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
              />
            }
            actions={[
              <PieChartOutlined
                key="setting"
                onClick={() => {
                  setTimeout(() => {
                    setVisible(true);
                    renderPieChart();
                  }, 0);
                }}
              />,
              // <EditOutlined key="edit" />,
              // <EllipsisOutlined key="ellipsis" />
            ]}
          >
            <Meta
              avatar={
                <Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />
              }
              title={username}
              description={
                <div>
                  <b>{region ? region : "全球"}</b>&nbsp;{roleName}
                </div>
              }
            />
          </Card>
        </Col>
      </Row>
      <div
        ref={barRef}
        style={{
          marginTop: "20px",
          width: "100%",
          height: "500px"
        }}
      ></div>
      <Drawer
        width="500"
        title="个人新闻数据分析"
        placement="right"
        onClose={() => {
          setVisible(false);
        }}
        visible={visible}
      >
        <div
          ref={pieRef}
          style={{
            marginTop: "20px",
            width: "100%",
            height: "500px"
          }}
        ></div>
      </Drawer>
    </div>
  );
}
